package com.geek688.auxiliarytool.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geek688.auxiliarytool.config.Config;
import com.geek688.auxiliarytool.util.FileUtil;

public class FileReplaceUI extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(FileReplaceUI.class);
	//后缀匹配的全部文件
	private static List<File> filelist = new ArrayList<>();
	//符合查找内容的文件
	private static List<File> contentlist = new ArrayList<>();
	//
	private List<String> newContentArr = new ArrayList<>();
	//文件后缀名
	private static List<String> suffix = new ArrayList<>();
	private boolean regexFlag = true;
	private List<String> regexArr = new ArrayList<>();
	//文件根目录
	private JFileChooser sourcePath = new JFileChooser();
	private JTextField outPathTF= null;
	private JTextArea regexArea = new JTextArea();
	private JTextArea newContentArea = new JTextArea();
	private JTextArea outArea = new JTextArea();
	private JRadioButton regexBtn,textBtn;
	private JComboBox<String> checkBox = null;
	
	public void drawUI(JTabbedPane tabPanel) {
		JPanel parent = new JPanel();
		checkBox = new JComboBox<>();
		checkBox.addItem("全部");
		checkBox.addItem("java");
		checkBox.addItem("jsp");
		checkBox.addItem("vue");
		checkBox.addItem("txt");
		checkBox.setActionCommand("check"); checkBox.addActionListener(this);
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JButton fileBtn = new JButton("路径");
		fileBtn.setPreferredSize(new Dimension(65, 30));
		fileBtn.setActionCommand("open");fileBtn.addActionListener(this);
		panel.add(fileBtn);
		panel.add(outPathTF = new JTextField());
		panel.add(new JLabel("文件格式"));panel.add(checkBox);
		outPathTF.setPreferredSize(new Dimension(260, 30));
//		panel.add(fileBtn);
		parent.add(panel);
		
		JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JButton scanBtn = new JButton("扫描");
		scanBtn.setActionCommand("scan");scanBtn.addActionListener(this);
		btnPanel.add(scanBtn);
		JButton runBtn = new JButton("替换");
		runBtn.setActionCommand("run");runBtn.addActionListener(this);
		btnPanel.add(runBtn);
		regexBtn = new JRadioButton("正则匹配");
		regexBtn.setActionCommand("regex");regexBtn.addActionListener(this);
		textBtn = new JRadioButton("文本匹配");
		textBtn.setActionCommand("text");textBtn.addActionListener(this);textBtn.setSelected(true);
		btnPanel.add(textBtn);
		btnPanel.add(regexBtn);
//		JButton runBtn = new JButton("替换");
//		runBtn.setActionCommand("run");runBtn.addActionListener(this);
//		btnPanel.add(runBtn);
		parent.add(btnPanel);
		
		JPanel jPanel = new JPanel(new GridLayout(1, 2));
		jPanel.setPreferredSize(new Dimension(750, 30));
		jPanel.add(new JLabel("查找的内容"));
		jPanel.add(new JLabel("替换的内容"));
		parent.add(jPanel);
		//需要查找的内容
//		JTextArea regexArea = new JTextArea();
//	    regexArea.setFont(new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,14));
        regexArea.setLineWrap(true);//自动换行
        regexArea.setForeground(Color.RED);
        regexArea.setBorder(BorderFactory.createLineBorder(Color.gray,1));//边框
        JScrollPane scrollPane = new JScrollPane(regexArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setViewportView(regexArea);
        scrollPane.setPreferredSize(new Dimension(375, 150));
        parent.add(scrollPane);
        //替换的新内容
//        JTextArea newContentArea = new JTextArea();
        newContentArea.setLineWrap(true);//自动换行
        newContentArea.setForeground(Color.RED);
        newContentArea.setBorder(BorderFactory.createLineBorder(Color.gray,1));//边框
        JScrollPane scrollPane2 = new JScrollPane(newContentArea);
        scrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane2.setViewportView(newContentArea);
        scrollPane2.setPreferredSize(new Dimension(375, 150));
        parent.add(scrollPane2);
        //输出窗口
//        JTextArea outArea = new JTextArea();
        outArea.setLineWrap(true);//自动换行
        outArea.setForeground(Color.RED);
        outArea.setBorder(BorderFactory.createLineBorder(Color.gray,1));//边框
        JScrollPane scrollPane3= new JScrollPane(outArea);
        scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane3.setViewportView(outArea);
        scrollPane3.setPreferredSize(new Dimension(750, 240));
        parent.add(new JLabel("输出窗口"));
        parent.add(scrollPane3);
        JPanel panela = new JPanel(new GridLayout(1, 2));
        panela.setPreferredSize(new Dimension(770, 15));
        panela.add(new JLabel("版本v1.0",JLabel.RIGHT));
        parent.add(panela);
        tabPanel.addTab("文本替换工具", parent);
	}
	public static List<File> getFileList(File dir){
        if(dir.exists()){
            File[] files = dir.listFiles((File pathname)-> {
                if(pathname.isDirectory()){
                    return true;
                }
                return check(pathname, suffix);
            });
            for(int i=0;i<files.length;i++){
                if(files[i].isFile()){
//                    files[i].delete();
                }else if(files[i].isDirectory()){
                	getFileList(files[i]);
                }else{
                	continue;
                }
            }
        }else{
            throw new RuntimeException("操作的文件或者目录不存在！");
        }
        return filelist;
    }
	
	/**
	 * 检测 文件是否包含指定内容
	 * @param file
	 * @param regex
	 */
	private static void check(File file,String regex){
		String content = FileUtil.getFileText(file.getAbsolutePath());
		content = content.replaceAll("(\r\n)|(\n)", "\\\\r\\\\n");//
		if (content.indexOf(regex) != -1) {
			contentlist.add(file);
		}
	}
	/**
	 * 检测 多类型后缀名
	 * @param name
	 * @param suffix2 后缀名数组
	 * @return
	 */
	private static boolean check(File name,List<String> suffix) {
		List<Boolean> result = new ArrayList<>();
		if (suffix == null || suffix.size()<=0) {
			return false;
		}
		for(String ends: suffix){
			if (name.getName().endsWith(ends)) {
				filelist.add(name);
			}
			result.add(name.getName().endsWith(ends));
		}
		int num = 0;
		for(Boolean b:result){
			if (!b) {
				num++;
				if (num == suffix.size()) {
					return false;
				}
			}
		}
		return true;
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("check")) {
			String item = (String) checkBox.getSelectedItem();
			if ("全部".equals(item)) {
				suffix.add(".java");
				suffix.add(".jsp");
				suffix.add(".vue");
				suffix.add(".txt");
			}else if ("java".equals(item)) {
				suffix.clear();
				suffix.add(".java");
			}else if ("jsp".equals(item)) {
				suffix.clear();
				suffix.add(".jsp");
			}else if ("txt".equals(item)) {
				suffix.clear();
				suffix.add(".txt");
			}else if ("vue".equals(item)) {
				suffix.clear();
				suffix.add(".vue");
			}
		}
		if (e.getActionCommand().equals("open")) {
			sourcePath.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			sourcePath.showOpenDialog(this);
			File f =  sourcePath.getSelectedFile();//使用文件类获取选择器选择的文件
			String s = f.getAbsolutePath().trim();//返回路径名
			outPathTF.setText(s);
		}
		if (e.getActionCommand().equals("run")) {
			logger.debug("符合要求的文件",contentlist);
			if(contentlist == null || contentlist.size()<=0){
				JOptionPane.showMessageDialog(this,"请扫描文件");//弹出对话框,显示选择结
				return ;
			}
			String text = newContentArea.getText();
//			if(StrUtil.isBlank(text)){
//				JOptionPane.showMessageDialog(this,"请输入替换的内容");//弹出对话框,显示选择结
//				return ;
//			}
			text = text.replaceAll("(\r\n)|(\n)", Config.CRLF);
			logger.debug("格式化后的文本："+Config.CRLF+text);
			newContentArr.add(text);
			String regex = regexArea.getText();
			if(StringUtils.isBlank(regex)){
				JOptionPane.showMessageDialog(this,"请输入查找的内容");//弹出对话框,显示选择结
				return ;
			}
			if (regexFlag) {
				regex = regex.replaceAll("(\r\n)|(\n)", "\\\\r\\\\n");
			}
			logger.debug("格式化后的文本："+Config.CRLF+regex);
			regexArr.add(regex);
			outArea.append("本次共扫描到 "+contentlist.size()+"个文件！"+Config.CRLF);
			new Thread(()->{
				int num=0;
				for(File file : contentlist){
					String[] oldChars = new String[regexArr.size()];
					String[] newChars = new String[newContentArr.size()];
					regexArr.toArray(oldChars);
					newContentArr.toArray(newChars);
					FileUtil.replaceFileText(file.getAbsolutePath(), oldChars, newChars);
					num++;
					outArea.append("正在处理第"+num+"个文件，文件名："+file.getName()+Config.CRLF);
					outArea.selectAll();
				}
				outArea.append("本次成功操作"+num+"个文件。");
			}).start();
		}
		if (e.getActionCommand().equals("scan")) {
			filelist.clear();
			contentlist.clear();
			regexArr.clear();
			newContentArr.clear();
			outArea.setText("");
			String text = outPathTF.getText();
			if(suffix.size()<=0){
				JOptionPane.showMessageDialog(this,"请选择需要扫描的文件类型！");//弹出对话框,显示选择结
				return ;
			}
			if(StringUtils.isBlank(text)){
				JOptionPane.showMessageDialog(this,"请选择目标路径");//弹出对话框,显示选择结
				return ;
			}
			String regex = regexArea.getText();
			if(StringUtils.isBlank(regex)){
				JOptionPane.showMessageDialog(this,"请输入查找的内容");//弹出对话框,显示选择结
				return ;
			}
			if (regexFlag) {
				regex = regex.replaceAll("(\r\n)|(\n)", "\\\\r\\\\n");
			}
			List<File> fileList2 = getFileList(new File(text));
			if (fileList2 != null){
				for (File file:fileList2){
					check(file, regex);
				}
			}
			for(File s:contentlist)outArea.append(s.getAbsolutePath()+Config.CRLF);
		}
		if (e.getActionCommand().equals("text")) {
			regexBtn.setSelected(!textBtn.isSelected());
			regexFlag = true;
		}
		if (e.getActionCommand().equals("regex")) {
			textBtn.setSelected(!regexBtn.isSelected());
			regexFlag = false;
		}
	}
	
}
